<template>
  <div class="main">
    <section>
      <el-tabs v-model="activeName">
        <el-tab-pane label="奖金配置列表" name="first">
          <div v-if="rightsButtons['add']" class="btn-block">
            <router-link :to="{name: 'boxBonusAdd'}">
              <el-button type="success" size="small" icon="el-icon-circle-plus" plain>新建奖金配置</el-button>
            </router-link>
          </div>
          <el-table v-loading="listLoading" :data="list" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column align="center" label="箱起奖金名称" prop="name"></el-table-column>
            <el-table-column align="center" label="生效时间" prop="startTime"></el-table-column>
            <el-table-column align="center" label="失效时间" prop="endTime"></el-table-column>
            <el-table-column align="center" label="状态" prop="configStatus" width="160">
              <template slot-scope="scope">
                <span v-if="scope.row.configStatus===0">活动中</span>
                <span v-else-if="scope.row.configStatus===1">未开始</span>
                <span v-else>已失效</span>
              </template>
            </el-table-column>
            <el-table-column v-if="rightsButtons['edit'] || rightsButtons['view'] || rightsButtons['hide']" align="center" label="操作" width="200">
              <template slot-scope="scope">
                <el-button v-if="rightsButtons['edit'] && (scope.row.configStatus===0||scope.row.configStatus===1)" type="primary" size="mini" @click="$router.push({ path: 'boxBonus/edit', query: { type: scope.row.configStatus, id: scope.row.bonusConfigId } })">编辑</el-button>
                <el-button v-if="rightsButtons['view'] && scope.row.configStatus===2" type="primary" size="mini" @click="$router.push({ path: 'boxBonus/view', query: { type: scope.row.configStatus, id: scope.row.bonusConfigId } })">查看</el-button>
                <el-button v-if="rightsButtons['hide']" type="primary" size="mini" @click="appShow(scope.row)">{{ scope.row.appShow===1?'隐藏':'显示' }}</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="listQuery.pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="listQuery.pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange">
          </el-pagination>
          <el-dialog :title="formData.id ? '编辑箱起活动' : '新建箱起活动'" :visible.sync="dialogFormVisible">
            <el-form ref="form" :model="formData" :rules="formRules" size="medium" label-width="120px">
              <el-form-item label="活动系列名称:" prop="seriesName">
                <el-input v-model="formData.seriesName"></el-input>
              </el-form-item>
              <el-form-item label="活动图片:" prop="img" class="banner-container">
                <el-upload
                  class="avatar-uploader"
                  accept="image/*"
                  :action="upladUrl"
                  name="file"
                  :show-file-list="false"
                  :on-success="uploadSuccess"
                  :before-upload="beforeUpload">
                  <img v-if="formData.img" :src="formData.img" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <!--<el-form-item label="排序:" prop="sort">
                        <el-input v-model="formData.sort" type="number"></el-input>
                    </el-form-item>-->
              <el-form-item label="是否上架:" prop="upshelf">
                <el-switch
                  v-model="formData.upshelf"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  @change="changeIsSell">
                </el-switch>
              </el-form-item>
              <el-form-item label="是否售卖:" prop="isSell">
                <el-switch
                  v-model="formData.isSell"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="0"
                  :disabled="!formData.upshelf">
                </el-switch>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" :loading="btnLoading" :disabled="btnLoading" @click="save">保存</el-button>
              <el-button @click="dialogFormVisible = false">取消</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="多奖金模式列表" name="second">
          <div v-if="rightsButtons['addLink']" class="btn-block">
            <el-button type="success" size="small" icon="el-icon-circle-plus" plain @click="moreBonusLink">新建奖金配置链接</el-button>
          </div>
          <el-table v-loading="moreBonusListLoading" :data="moreBonusList" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" type="index" label="序号" width="80">
            </el-table-column>
            <el-table-column align="center" label="奖金模型名称" prop="name"></el-table-column>
            <el-table-column align="center" label="主奖金模型" prop="bonusConfigMasterName"></el-table-column>
            <el-table-column align="center" label="副奖金模型" prop="bonusConfigSlaveName"></el-table-column>
            <el-table-column align="center" label="生效时间" prop="startTime"></el-table-column>
            <el-table-column align="center" label="失效时间" prop="endTime"></el-table-column>
            <el-table-column align="center" label="状态" prop="configStatus" width="160">
              <template slot-scope="scope">
                <span v-if="scope.row.configStatus===0">活动中</span>
                <span v-else-if="scope.row.configStatus===1">未开始</span>
                <span v-else>已失效</span>
              </template>
            </el-table-column>
            <el-table-column v-if="rightsButtons['editMoreBonus'] || rightsButtons['viewMoreBonus'] || rightsButtons['hideMoreBonus']" align="center" label="操作" width="250">
              <template slot-scope="scope">
                <el-button v-if="rightsButtons['editMoreBonus'] && (scope.row.configStatus===0||scope.row.configStatus===1)" type="primary" size="mini" @click="moreBonusUpdate(scope.row,null)">编辑</el-button>
                <el-button v-if="rightsButtons['viewMoreBonus'] && scope.row.configStatus===2" type="primary" size="mini" @click="moreBonusUpdate(scope.row,null,'look')">查看</el-button>
                <el-button v-if="rightsButtons['hideMoreBonus']" type="primary" size="mini" @click="moreBonusUpdate(scope.row,(scope.row.appShow===0?1:0))">{{ scope.row.appShow===0?'显示':'隐藏' }}</el-button>
                <el-button v-if="rightsButtons['delMoreBonus']" type="primary" size="mini" @click="del(scope.row)" :disabled="scope.row.configStatus===2">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            background
            :current-page.sync="moreBonusListQuery.pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="moreBonusListQuery.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="moreBonusListTotal"
            @size-change="moreBonusSizeChange"
            @current-change="moreBonusCurrentChange">
          </el-pagination>
          <el-dialog title="设置" :visible.sync="moreBonusDialogVisible">
            <el-form ref="moreBonusFormRef" :model="moreBonusFormData" label-width="150px">
              <el-form-item label="奖金模型名称:" prop="name" :rules="commonRules.notNullRule">
                <el-input v-model="moreBonusFormData.name" placeholder="请输入奖金模型名称" :disabled="moreBonusDialogDisable"></el-input>
              </el-form-item>
              <el-form-item v-if="!bonusConfigLinkId" label="选择主奖金模型:" prop="bonusConfigMasterId" :rules="commonRules.notNullRule">
                <el-select v-model="moreBonusFormData.bonusConfigMasterId" placeholder="请选择">
                  <el-option v-for="item in moreBonusDialogData.masterList" :key="item.id" :label="item.name" :value="item.bonusConfigId"></el-option>
                </el-select>
                <span style="color:red">主奖金模型业绩封顶计算</span>
              </el-form-item>
              <el-form-item v-if="bonusConfigLinkId" label="选择主奖金模型:" prop="bonusConfigMasterId" :rules="commonRules.notNullRule">
                <el-input v-model="moreBonusFormData.bonusConfigMasterName" :disabled="true"></el-input>
                <span style="color:red">主奖金模型业绩封顶计算</span>
              </el-form-item>
              <el-form-item v-if="!bonusConfigLinkId" label="选择副奖金模型:" prop="bonusConfigSlaveId" :rules="commonRules.notNullRule">
                <el-select v-model="moreBonusFormData.bonusConfigSlaveId" placeholder="请选择">
                  <el-option v-for="item in moreBonusDialogData.slaveList" :key="item.id" :label="item.name" :value="item.bonusConfigId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="bonusConfigLinkId" label="选择副奖金模型:" prop="bonusConfigSlaveId" :rules="commonRules.notNullRule">
                <el-input v-model="moreBonusFormData.bonusConfigSlaveName" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="有效时间:" prop="timeDate" :rules="commonRules.notNullRule">
                <template>
                  <el-date-picker
                    v-model="moreBonusFormData.timeDate"
                    :disabled="moreBonusDialogDisable"
                    type="monthrange"
                    range-separator="至"
                    start-placeholder="开始月份"
                    end-placeholder="结束月份"
                    value-format="yyyy-MM-dd HH:mm:ss">
                  </el-date-picker>
                </template>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="confirm(bonusConfigLinkId!=''?'edit':'add')">确定</el-button>
              <el-button @click="moreBonusDialogVisible = false">取消</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
      </el-tabs>
    </section>
  </div>
</template>
<script>
import { debounce } from '../../../utils/index'
export default {
  name: 'BoxBonus',
  data() {
    return {
      activeName: 'first',
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        isPage: 1
      },
      listLoading: false,
      list: [],
      listTotal: 0,

      dialogFormVisible: false,
      btnLoading: false,
      formData: {
        seriesName: '',
        img: '',
        sort: '',
        upshelf: 1,
        isSell: 1
      },
      formRules: {
        seriesName: [{ required: true, message: '不能为空', trigger: 'change' }],
        img: [{ required: true, message: '请上传活动图片' }]
      },
      moreBonusListLoading: false,
      moreBonusList: [],
      moreBonusListQuery: {
        pageIndex: 1,
        pageSize: 10
      },
      moreBonusListTotal: 0,
      bonusConfigLinkId: '',
      moreBonusFormData: {
        name: '',
        bonusConfigMasterId: '',
        bonusConfigSlaveId: '',
        startTime: '',
        endTime: '',
        appShow: null,
        timeDate: [],
        bonusConfigMasterName: '',
        bonusConfigSlaveName: ''
      },
      moreBonusDialogData: {
        bonusConfigMasterName: '',
        bonusConfigSlaveName: '',
        masterList: [],
        slaveList: [],
        timeDate: []
      },
      moreBonusDialogVisible: false,
      moreBonusDialogDisable: false
    }
  },
  created() {
    this.getList()
    this.getMoreBonusList()
  },
  activated() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.request({
        url: '/bsnl-product/box/bonus/config/list',
        method: 'post',
        data: this.listQuery
      }).then(({ data, total }) => {
        this.list = data
        this.listTotal = total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.list = []
        this.listTotal = 0
        this.listLoading = false
      })
    },
    appShow(row) {
      this.request({
        url: '/bsnl-product/box/bonus/config/show',
        method: 'post',
        data: {
          bonusConfigId: row.bonusConfigId,
          appShow: row.appShow === 1 ? 0 : 1
        }
      }).then((res) => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.getList()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleSizeChange(value) {
      this.listQuery.pageSize = value
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageIndex = val
      this.getList()
    },
    showAdd() {
      this.formData = {
        seriesName: '',
        img: '',
        sort: '',
        upshelf: 1,
        isSell: 1
      }
      this.dialogFormVisible = true
      this.btnLoading = false
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    showEdit(row) {
      this.formData = Object.assign({}, row)
      this.dialogFormVisible = true
      this.btnLoading = false
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    uploadSuccess(res) {
      this.formData.img = this.replaceImgUrl(res.filePath)
    },
    changeIsSell() {
      this.formData.isSell = this.formData.upshelf && this.formData.isSell
    },
    save: debounce(function() {
      this.$refs.form.validate(valid => {
        if (!valid || this.btnLoading) {
          return false
        }

        this.btnLoading = true
        this.request({
          url: '/bsnl-product/box/doSave',
          method: 'post',
          data: this.formData
        }).then(() => {
          this.btnLoading = false
          this.dialogFormVisible = false
          this.$message.success('保存成功')
          this.getList()
        }).catch(err => {
          this.btnLoading = false
        })
      })
    }, 1500, true),
    getMoreBonusList() {
      this.moreBonusListLoading = true
      this.request({
        url: '/bsnl-product/box/bonus/config/link/list',
        method: 'post',
        data: this.moreBonusListQuery
      }).then(({ data, total }) => {
        this.moreBonusList = data
        this.moreBonusListTotal = total
        this.moreBonusListLoading = false
      }).catch(err => {
        console.log(err)
        this.moreBonusList = []
        this.moreBonusListTotal = 0
        this.moreBonusListLoading = false
      })
    },
    moreBonusSizeChange(value) {
      this.moreBonusListQuery.pageSize = value
      this.getMoreBonusList()
    },
    moreBonusCurrentChange(val) {
      this.moreBonusListQuery.pageIndex = val
      this.getMoreBonusList()
    },
    // 新建奖金配置链接
    moreBonusLink() {
      this.moreBonusDialogVisible = true
      this.moreBonusDialogDisable = false
      this.bonusConfigLinkId = ''
      this.moreBonusFormData = {}
      this.masterAndslave()
      this.$nextTick(()=>{
          this.$refs.moreBonusFormRef.clearValidate()
      })
    },
    // 主(副)奖金配置列表
    masterAndslave() {
      this.request({
        url: '/bsnl-product/box/bonus/config/master-slave/list',
        method: 'post'
      }).then((res) => {
        if (res.status == 200) {
          this.moreBonusDialogData.masterList = res.data.masterList
          this.moreBonusDialogData.slaveList = res.data.slaveList
        }
      }).catch(err => {
        console.log(err)
      })
    },
    effectiveTime() {
      if(this.moreBonusFormData && this.moreBonusFormData.timeDate){
        const endMonth = this.formatDate(this.moreBonusFormData.timeDate[1], 'YYYY-MM')
        const endDate = new Date(endMonth)
        let month = endDate.getMonth()
        const nextMonth = ++month
        const nextMonthFirstDay = new Date(endDate.getFullYear(), nextMonth, 1)
        const oneDay = 1000 * 60 * 60 * 24
        const dateString = new Date(nextMonthFirstDay - oneDay).toLocaleDateString()
        const endTime = dateString.replace(new RegExp('/', 'g'), '-')
        this.moreBonusFormData.startTime = this.moreBonusFormData.timeDate[0]
        this.moreBonusFormData.endTime = this.formatDate(endTime, 'YYYY-MM-DD') + ' 23:59:59'
        this.moreBonusFormData.timeDate = [this.moreBonusFormData.startTime, this.moreBonusFormData.endTime]
      }
    },
    moreBonusAdd() {
      this.effectiveTime()
      this.$refs.moreBonusFormRef.validate(valid => {
        if (!valid) {
          return false
        }
        this.request({
          url: '/bsnl-product/box/bonus/config/link/add',
          method: 'post',
          data: this.moreBonusFormData
        }).then((res) => {
          if (res.status == 200) {
            this.moreBonusDialogVisible = false
            this.getMoreBonusList()
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    moreBonusUpdate(data, appShow, show) {
      this.moreBonusDialogDisable = show === 'look'
      this.moreBonusDialogVisible = appShow === null
      if(this.moreBonusDialogVisible){
        this.$nextTick(()=>{
          this.$refs.moreBonusFormRef.clearValidate()
        })
      }
      this.bonusConfigLinkId = data.bonusConfigLinkId
      this.moreBonusFormData.timeDate = [data.startTime, data.endTime]
      this.moreBonusFormData = {
        name: data.name,
        bonusConfigMasterId: data.bonusConfigMasterId,
        bonusConfigSlaveId: data.bonusConfigSlaveId,
        appShow: appShow,
        timeDate: [data.startTime, data.endTime],
        bonusConfigMasterName: data.bonusConfigMasterName,
        bonusConfigSlaveName: data.bonusConfigSlaveName
      }
       if (appShow !== null) {
         this.moreBonusUpdateInterface('iSShow')
       }
    },
    moreBonusUpdateInterface(iSShow) {
      this.effectiveTime()
      if (iSShow) {
        this.request({
          url: '/bsnl-product/box/bonus/config/link/update',
          method: 'post',
          data: {
            ...this.moreBonusFormData,
            bonusConfigLinkId: this.bonusConfigLinkId
          }
        }).then((res) => {
          if (res.status == 200) {
            this.moreBonusDialogVisible = false
            this.getMoreBonusList()
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.$refs.moreBonusFormRef.validate(valid => {
          if (!valid) {
            return false
          }
          this.request({
            url: '/bsnl-product/box/bonus/config/link/update',
            method: 'post',
            data: {
              ...this.moreBonusFormData,
              bonusConfigLinkId: this.bonusConfigLinkId
            }
          }).then((res) => {
            if (res.status == 200) {
              this.moreBonusDialogVisible = false
              this.getMoreBonusList()
            }
          }).catch(err => {
            console.log(err)
          })
        })
      }
    },
    confirm(params) {
      if (params === 'add') {
        this.moreBonusAdd()
      } else {
        this.moreBonusUpdateInterface()
      }
    },
    del(item) {
      this.$confirm('删除后该奖金模型将失效且自动解除链接，是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request({
          url: '/bsnl-product/box/bonus/config/link/delete',
          method: 'get',
          params: {
            configLinkId:item.bonusConfigLinkId
          }
        }).then((res) => {
          if (res.status == 200) {
            this.$message.success('删除成功')
            this.getMoreBonusList()
          }
        }).catch(err => {
          console.log(err)
        })
      })
    }
  }
}
</script>
<style lang="scss">
    @import "../../../styles/mixin";
    .banner-container{
        .avatar-uploader .el-upload{
            width: 120px;
            height: 120px;
            line-height: 118px;
        }
    }
    .activity-img{
        @include flex;
        @include center;
        min-height: 60px;
        img{
            width:100%;
            height: 100%;
            max-width: 60px;
            max-height: 60px;
        }
    }
    .el-row{
        margin-bottom: 12px;
    }
</style>
